package com.xnx3.wangmarket.admin.controller;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.xnx3.j2ee.func.AttachmentFile;
import com.xnx3.j2ee.service.SqlService;
import com.xnx3.j2ee.vo.BaseVO;
import com.xnx3.j2ee.vo.UploadFileVO;
import com.xnx3.wangmarket.Utils.FileUtil;
import com.xnx3.wangmarket.Utils.ServerAddressUtils;
import com.xnx3.wangmarket.admin.entity.*;
import com.xnx3.wangmarket.admin.service.CompanyInfoService;
import com.xnx3.wangmarket.admin.service.SiteColumnService;
import com.xnx3.wangmarket.admin.util.AliyunLog;
import com.xnx3.wangmarket.admin.vo.CompanyInfoVo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.xnx3.j2ee.shiro.ShiroFunc.getUserId;

@Controller
@RequestMapping("/CompanyInfoController")
public class CompanyInfoController {

    @Resource
    private SqlService sqlService;
    @Resource
    private CompanyInfoService companyInfoService;
    @Resource
    private SiteColumnService siteColumnService;
    private String userid;
    private String broadcastImge;

    @RequestMapping("/queryOneColumn.do")
    @ResponseBody
    public Map<String, Object> queryOneColumn(Model model, HttpServletRequest request) {
        int count=0;
        SiteColumn siteColumn = new SiteColumn();
        userid = request.getParameter("userid");
        if (userid != null && !"".equals(userid)) {
//            获取网站访问量
           int id= Integer.parseInt(userid);
           List<Site> sites = companyInfoService.queryNum(id);

               for (Site site:sites) {
                   count = site.getCountNum()+1;
               }
               companyInfoService.updateCountNum(id,count);

            siteColumn.setUserid(Integer.parseInt(userid));
            //获取所有栏目
            List<SiteColumn> columnList = siteColumnService.queryAllColumn(siteColumn);

            //siteColimnList的最高一级
            List<SiteColumn> columns = new ArrayList<>();
            for (SiteColumn s : columnList) {
                if (s.getParentid() == null || s.getParentid() == 0) {
                    columns.add(s);
                }
            }
            getAllSiteColumn(columnList, columns);
            //获取二级栏目
            List<SiteColumn> siteTwoColumn = siteColumnService.queryTwoColumn(siteColumn);
            List list = new ArrayList();
            Integer siteId = null;
            for (SiteColumn siteColumnId : columnList) {
                siteId = siteColumnId.getSiteid();
            }
//            System.out.println("测试二级菜单:"+columns);
            //获取网站title
            List<Site> siteList = siteColumnService.queryTitle(siteId);
            String siteName = null;
            String phone = null;
            String companyName = null;
            String logo = null;
            String qq = null;
            String address = null;
            String companyEmail = null;
            Integer hotline = null;
            String title = null;
//            String broadcastImgPath = null;
            for (Site site : siteList) {
                siteName = site.getName();
                phone = site.getPhone();
                companyName = site.getCompanyName();
                logo = site.getLogo();
                qq = site.getQq();
                hotline = site.getHotLine();
                address = site.getAddress();
                companyEmail = site.getCompanyEmail();
                title = site.getName();
//                broadcastImgPath = site.getBroadcastImgPath();
            }
            int cId = 0;

            List<CompanyInfo> companyInfos = companyInfoService.queryCompanyInfo(Integer.parseInt(userid));
//轮播地址分开，存入list中
//            String[] arr = broadcastImgPath.split(";");
            List<String> pathList = new ArrayList<>();
            for (CompanyInfo companyInfo : companyInfos) {
                pathList.add(companyInfo.getBroadcastImgPath());
            }

            Map<String, Object> map = new HashMap<>();
            // model.addAttribute("products",products);
            if (!columnList.isEmpty() && !siteList.isEmpty()) {
                map.put("title", title);
                map.put("columnList", columns);
                map.put("siteName", siteName);
                map.put("phone", phone);
                map.put("companyName", companyName);
                map.put("logo", logo);
                map.put("qq", qq);
                map.put("hotline", hotline);
                map.put("address", address);
                map.put("companyEmail", companyEmail);
                map.put("cid", cId);
                map.put("broadcastImgPath", pathList);
            }
            return map;
        }
        return null;
    }

    //获取产品信息
    @RequestMapping("/product.do")
    @ResponseBody
    public Map<String, Object> product(@RequestParam(value = "siteColId", required = false) String siteColId) {

        Map<String, Object> map = new HashMap<>();
        if (userid != null && !"".equals(userid)) {
            //产品信息
            if (siteColId != null && !"".equals(siteColId)) {
                List<Product> productList = companyInfoService.twoSelProduct(Integer.parseInt(siteColId), Integer.parseInt(userid));
                map.put("products", productList);
            } else {
                List<Product> products = companyInfoService.queryProduct(Integer.parseInt(userid));
                map.put("products", products);
            }
            return map;
        }
        return null;
    }

    //实验结论
    @RequestMapping("/empirical.do")
    @ResponseBody
    public Map<String, Object> empirical(@RequestParam(value = "siteColId", required = false) String siteColId) {

        Map<String, Object> map = new HashMap<>();
        if (userid != null && !"".equals(userid)) {
            if (siteColId != null && !"".equals(siteColId)) {
                List<EmpiricalConclusion> empiricalList = companyInfoService.twoSelEmpircal(Integer.parseInt(siteColId), Integer.parseInt(userid));
                map.put("empirical", empiricalList);
            } else {
                List<EmpiricalConclusion> empirical = companyInfoService.queryEmpirical(Integer.parseInt(userid));
                map.put("empirical", empirical);
            }
            return map;
        }
        return null;
    }

    //循环获取sitColumn的子集
    private void getAllSiteColumn(List<SiteColumn> siteColumns, List<SiteColumn> siteColumnsClone) {
        //子集list
        for (SiteColumn sc : siteColumnsClone) {
            //循环给list附上子集
            List<SiteColumn> newSiteCloumns = new ArrayList<>();
            //循环最大的集合
            for (SiteColumn s : siteColumns) {
                if (sc.getId().equals(s.getParentid())) {
                    //加上子集
                    newSiteCloumns.add(s);
                }
            }
            //递归赋值
            getAllSiteColumn(siteColumns, newSiteCloumns);
            sc.setSiteColumnChildren(newSiteCloumns);
        }
    }

    /***
     * 其他内容
     * **/
    @RequestMapping("/description.do")
    @ResponseBody
    public Map<String, Object> description(@RequestParam(value = "id", required = false) String id, @RequestParam(value = "userid", required = false) String userid) {
        List<News> newsList = companyInfoService.queryNewList(Integer.parseInt(userid), Integer.parseInt(id));
        Map<String, Object> map = new HashMap<String, Object>();
        if (!newsList.isEmpty()) {
            for (News n : newsList) {
                List<NewsData> newsData = companyInfoService.queryNewsData(n.getId());
                map.put("id", n.getId());
                map.put("title", n.getTitle());
                map.put("titlepic", n.getTitlepic());
                map.put("intro", n.getIntro());
                for (NewsData news : newsData) {
                    if (news.getId().equals(n.getId())) {
                        map.put("newsText", news.getText());
                    }
                }
            }
        }
        return map;
    }

    /***
     * 新闻栏目
     * **/
    @RequestMapping("/NewsColumn.do")
    @ResponseBody
    public Map<String, Object> NewsColumn() {
        List<SiteColumn> listNewsColumn = null;
        List<SiteColumn> oneColumn = companyInfoService.queryNewsOneColumn(Integer.parseInt(userid));
        for (SiteColumn siteColumn : oneColumn) {
            if (siteColumn.getParentid() > 0) {
                listNewsColumn = companyInfoService.queryNewsTwoColumn(siteColumn.getParentid(), Integer.parseInt(userid));
            }
        }
        if (!listNewsColumn.isEmpty()) {
            Map<String, Object> map = new HashMap<>();
            map.put("listNewsColumn", listNewsColumn);
            return map;
        }
        return null;
    }

    /***
     * 新闻内容和标题
     * **/
    @RequestMapping("/news.do")
    @ResponseBody
    public Map<String, Object> news(@RequestParam(value = "cid", required = false) String cid) {

        if (userid != null && !"".equals(userid) && cid != null && !"".equals(cid)) {
            List<News> news = companyInfoService.queryAllNews(Integer.parseInt(userid), Integer.parseInt(cid));
            for (News n : news) {
                if (!news.isEmpty()) {
                    List<NewsData> newsData = companyInfoService.queryNewsData(n.getId());
                    n.setSiteNewsChildren(newsData);
                }
            }
            if (!news.isEmpty()) {
                Map<String, Object> map = new HashMap<>();
                map.put("news", news);
                return map;
            }
        }
        return null;
    }

    /***
     * 产品二级查询
     * ****/
    @RequestMapping("/twoSelect.do")
    @ResponseBody
    public Map<String, Object> twoSelect(@RequestParam(value = "siteColId", required = false) String siteColId) {
        Map<String, Object> map = new HashMap<>();
        List<Product> twoSelProductList;
        List<EmpiricalConclusion> twoEmpiricalList;
        if (userid != null && !"".equals(userid) && siteColId != null && !"".equals(siteColId)) {

            twoSelProductList = companyInfoService.twoSelProduct(Integer.parseInt(siteColId), Integer.parseInt(userid));
            if (twoSelProductList.isEmpty()) {
                twoEmpiricalList = companyInfoService.twoSelEmpircal(Integer.parseInt(siteColId), Integer.parseInt(userid));
                if (twoEmpiricalList.isEmpty()) {
                    return null;
                } else {
                    map.put("twoEmpiricalList", twoEmpiricalList);
                }
            } else {
                map.put("twoSelProductList", twoSelProductList);
            }
        }

        return null;
    }

    /**
     * 上传图片接口
     */
    @RequestMapping(value = "uploadImage${url.suffix}", method = RequestMethod.POST)
    @ResponseBody
    public UploadFileVO uploadImage(Model model, HttpServletRequest request) {

        UploadFileVO uploadFileVO = AttachmentFile.uploadImage("site/" + getUserId() + "/news/broadcastImge/", request, "file", 0);
        if (uploadFileVO.getResult() == UploadFileVO.SUCCESS) {
            //上传成功，写日志
            broadcastImge = uploadFileVO.getPath();
            AliyunLog.addActionLog(getUserId(), "内容管理上传图片成功：" + uploadFileVO.getFileName(), uploadFileVO.getPath());
        }
        return uploadFileVO;
    }

    @RequestMapping("/queryBroadcasts.do")
    public String queryBroadcasts(Model model) {

        List<CompanyInfo> companyList = companyInfoService.queryCompanyInfo(getUserId());

        if (!companyList.isEmpty()) {
            model.addAttribute("broadcastImgPath", companyList);
        }
        return "site/BroadcastManagement";
    }

    //产品数据获取
    @RequestMapping("/companyAddList.do")
    public String companyAddList(Model model, HttpServletRequest request) {

        if (request.getParameter("id") != null && !"".equals(request.getParameter("id"))) {
            String cinfoId = request.getParameter("id");
            if (Integer.parseInt(cinfoId) > 0) {
                CompanyInfo cif = sqlService.findById(CompanyInfo.class, Integer.parseInt(cinfoId));
                model.addAttribute("cif", cif);
            }
        }
        return "site/BroadcastAdd";
    }

    //更新、新增轮播图
    @RequestMapping("/updateBroadcasts.do")
    @ResponseBody
    public CompanyInfoVo updateBroadcasts(CompanyInfo cif, @RequestParam(value = "id", required = false) String comId, HttpServletRequest request) {

        CompanyInfo companyInfo = new CompanyInfo();
        CompanyInfoVo companyInfoVo = new CompanyInfoVo();
        SimpleDateFormat sdft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateTime = sdft.format(new Date().getTime());

        if (comId != null && !"".equals(comId)) {
            Integer cid = Integer.parseInt(comId);
            if (cid > 0) {
                CompanyInfo cinfo = sqlService.findById(CompanyInfo.class, cid);
                if (cinfo.getId() == cid) {
                    if (broadcastImge != null && !"".equals(broadcastImge)) {
                        cinfo.setBroadcastImgPath(broadcastImge);
                    }
                    cinfo.setModifyTime(dateTime);
                    cinfo.setUserId(getUserId());
                    companyInfoService.updateCompanyInfo(cinfo, cid, request);
                    companyInfoVo.setBaseVO(BaseVO.SUCCESS, cif.getId() > 0 ? "保存成功！" : "创建成功！");
                    companyInfoVo.setCompanyInfo(cif);
                }
            }
        } else {
            List<CompanyInfo> companyInfos = companyInfoService.queryCompanyInfo(getUserId());
            if (companyInfos.size() + 1 <= 10) {
                companyInfo.setModifyTime(dateTime);
                companyInfo.setBroadcastImgPath(broadcastImge);
                companyInfo.setUserId(getUserId());
                companyInfo.setTimestamps(dateTime);
                companyInfoService.updateCompanyInfo(companyInfo, getUserId(), request);
                companyInfoVo.setBaseVO(BaseVO.SUCCESS, companyInfo.getId() > 0 ? "保存成功！" : "创建成功！");
                companyInfoVo.setCompanyInfo(companyInfo);
            } else {
                companyInfoVo.setBaseVO(BaseVO.FAILURE, "上传出错，轮播图最多只能上传10张！");
            }
        }
        broadcastImge = "";
        return companyInfoVo;
    }

    //删除轮播图
    @RequestMapping("/delBroadcasts.do")
    @ResponseBody
    public CompanyInfoVo delBroadcasts(HttpServletRequest request, @RequestParam(value = "id", required = false) String id) {

        CompanyInfoVo cinfoVo = new CompanyInfoVo();
        if (id != null && !"".equals(id)) {
            int cid = Integer.parseInt(id);
            CompanyInfo cinfo = new CompanyInfo();
            cinfo.setId(cid);
            CompanyInfo companyInfo = sqlService.findById(CompanyInfo.class, cid);

            FileUtil.deleteFile(ServerAddressUtils.tomcatPath(request) + companyInfo.getBroadcastImgPath());
            companyInfoService.delCompanyInfo(cinfo);

            cinfoVo.setBaseVO(BaseVO.SUCCESS, Integer.parseInt(id) > 0 ? "保存成功！" : "创建成功！");
            cinfoVo.setCompanyInfo(cinfo);
        } else {
            cinfoVo.setBaseVO(BaseVO.FAILURE, "删除失败！");
        }
        return cinfoVo;
    }

    @RequestMapping("/allProduct.do")
    @ResponseBody
    public Map<String, Object> allProduct() {
        List<Product> list = companyInfoService.allProduct();
        List<Integer> useridList = new ArrayList<>();
        HashMap<Integer,Site> siteHashMap = new HashMap<>();
        List<Site> sites = new ArrayList<>();
        for (Product pct:list) {
            List<Site> tempsites = new ArrayList<>();
            if(!useridList.contains(pct.getUserId())){
                List<Product> products = new ArrayList<>();
                useridList.add(pct.getUserId());
                tempsites = companyInfoService.querySite(pct.getUserId());
                products.add(pct);
                tempsites.get(0).setProductList(products);
                siteHashMap.put(pct.getUserId(),tempsites.get(0));
            }else{
                siteHashMap.get(pct.getUserId()).getProductList().add(pct);
            }
        }
        sites.addAll(siteHashMap.values());
        Map<String, Object> map = new HashMap<>();
//        map.put("product", list);
        map.put("siteInfo",sites);
        return map;
    }

    /**
     * 简单生成二维码，返回到页面上，废弃
     *
     * @param response
     */
    @RequestMapping(value = "/getErWeiCode.do", method = {RequestMethod.POST, RequestMethod.GET})
    public void getErWeiCode(HttpServletResponse response) {
        String url = "http://118.25.235.213:8030/rfpf/#/mains/" + getUserId();

        if (url != null && !"".equals(url)) {
            ServletOutputStream stream = null;
            try {
                int width = 400;
                int height = 400;
                stream = response.getOutputStream();
                QRCodeWriter writer = new QRCodeWriter();
                BitMatrix m = writer.encode(url, BarcodeFormat.QR_CODE, height, width);

                MatrixToImageWriter.writeToStream(m, "png", stream);

            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            } finally {
                if (stream != null) {
                    try {
                        stream.flush();
                        stream.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            }
        }
    }
    @RequestMapping("/countNum.do")
    @ResponseBody
    public List<Site> countNum(){

        return companyInfoService.queryCountNum();
    }

    /***
     * 查询最美乡村
     * **/
    @RequestMapping("zmxc.do")
    @ResponseBody
    public  Map<String,Object> zmxc(int page){
      Map<String,Object> map = new HashMap<>();
        int countPage = 10;
        News news = new News();
        Page pg = companyInfoService.findNewsPage(page,countPage,news);
        map.put("zmxcList",pg);
        return map;
    }

    /**
     * 查询服务示范
     * **/
    @RequestMapping("/getServiceDemonstration.do")
    @ResponseBody
    public Map<String,Object> getServiceDemonstration(String areaCode){

        return companyInfoService.getServiceDemonstration(areaCode);
    }

    /**
     * 查询服务示范点击更多
     * **/
    @RequestMapping("/getPageServiceDemonstration.do")
    @ResponseBody
    public Map<String,Object> getPageServiceDemonstration(Site site,int page,int num){

        Map<String,Object> map = new HashMap<>();

        Page pg = companyInfoService.findSitePage(site,page,num);
        map.put("zmxcList",pg);
        return map;
    }

}
